package sa.com.sure.ejtimaa.database;


import sa.com.sure.ejtimaa.common.AppHelper;
import sa.com.sure.ejtimaa.model.MeetingPlaceInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;


public class MeetingPlaces {

	private DataBaseHelper dbHelper;
	
	public static final String TABLE_Name = "MeetingPlaces";
	
    public static final String MeetingPlaceIDField = "MeetingPlaceID"; 
    public static final String MeetingPlaceNameField = "MeetingPlaceName";
    
    private String[] allColumns = { MeetingPlaceIDField, MeetingPlaceNameField  };
    
    Cursor cursor = null;    
    
    public MeetingPlaces(Context context)  {
 		dbHelper = new DataBaseHelper(context);
 		dbHelper.createDataBase();
 	}
    
        
    public static MeetingPlaces Instance = new MeetingPlaces(AppHelper.getAppContext());
    
	public void open() throws SQLException {
		dbHelper.openDataBase();
	}
	
	public void close() {
		
		if(cursor!=null && !cursor.isClosed())
		{
			cursor.close();
		}
		dbHelper.close();
		
	}
	
	public void addItem(MeetingPlaceInfo item) { 
        
		try
		{
		
			open();
			
	        ContentValues values = new ContentValues(); 
	        
	        values.put(MeetingPlaceIDField, item.GetMeetingPlaceID()); 
	        values.put(MeetingPlaceNameField, item.GetMeetingPlaceName()); 
	        
	        dbHelper.db.insert(TABLE_Name, null, values); 
                
		}
		finally{
			
			close();
		}
    } 
	
	
	public MeetingPlaceInfo GetItem(int MeetingPlaceID) throws SQLException{
	
		try{
			open();
		
			MeetingPlaceInfo item= null; 
			
			cursor = dbHelper.db.query( TABLE_Name,allColumns, MeetingPlaceIDField + "=" + MeetingPlaceID,null,null,null,null);
	        if (cursor != null ) {
	        	cursor.moveToFirst();	
	        	if(cursor.getCount()>0)
	        		item =   getItemInfo(cursor);
	        	
	        }	                
	        
	    	return item;
		}
		finally{
			
			close();
		}	    	
		    
	}

	 public boolean updateItem(MeetingPlaceInfo item) {
		 
		 try{
		 	open();
		 	
		    ContentValues args = new ContentValues();		    
		    args.put(MeetingPlaceNameField, item.GetMeetingPlaceName());		    
		    boolean res =   dbHelper.db.update(TABLE_Name, args, MeetingPlaceIDField + "=" + item.GetMeetingPlaceID() , null) > 0;
		    
		    return res;
		}
		finally{
			
			close();
		}		    
	 }
	
	
    private MeetingPlaceInfo getItemInfo(Cursor cursor) {  
  
    	return new MeetingPlaceInfo(cursor.getInt(0),cursor.getString(1));    	   
	}
}
